package ljye.com.ljye.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;

/**
 * Created by Administrator on 2016/12/28.
 */

public class MyHorizontalScrollView extends HorizontalScrollView {
    private OnScollChangedListener onScollChangedListener = null;
    private HorizontalScrollView mScroller;


    public MyHorizontalScrollView(Context context) {
        super(context);
        mScroller = new HorizontalScrollView(context);
    }

    public MyHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setOnScollChangedListener(OnScollChangedListener onScollChangedListener) {
        this.onScollChangedListener = onScollChangedListener;
    }

    @Override
    protected int computeHorizontalScrollOffset() {
        return super.computeHorizontalScrollOffset();
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (onScollChangedListener!=null){
            onScollChangedListener.onScrollChanged(this,x, y, oldx, oldy);

        }
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                Log.d("CCC", "按下");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d("CCC", "移动");
                break;
            case MotionEvent.ACTION_UP:
                Log.d("CCC", "抬起");
                if (onScollChangedListener!=null) {
                    onScollChangedListener.isUp();
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
//        if (deltaX<=2&&deltaX>=-2&&!isTouchEvent){
        if (deltaX==1&&deltaX==-1&&!isTouchEvent){
            onScollChangedListener.isStatic();
            //注意deltaX的值和isTouchEvent的值，deltaX可以认为是X轴变化的速度，isTouchEvent意思是移动事件是否来自手势。
            // 经过多次确认，当deltaX的值为1，2或-1，-2，以及isTouchEvent值为false的时候，scrollView的移动趋于停止
        }
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    public interface OnScollChangedListener{
        void onScrollChanged(MyHorizontalScrollView scrollView, int x, int y, int oldx, int oldy);
        void isUp();
        void isStatic();
    }

}
